<?php

namespace app\admin\controller\dahuinew;

use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\Exception;

/**
 * 代理记账业务记录管理
 *
 * @icon fa fa-circle-o
 */
class Dljzyw extends Backend
{
    
    /**
     * Dljzyw模型对象
     * @var \app\admin\model\dahuinew\Dljzyw
     */
    protected $model = null;

    protected $noNeedRight = ['changezcstatus', 'changesbstatus', 'getdsinfo', "yjxf",'import1','index2'];


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\dahuinew\Dljzyw;
        $this->view->assign("shuizList", $this->model->getShuizList());
        $this->view->assign("kpywList", $this->model->getKpywList());
        $this->view->assign("isxyList", $this->model->getIsxyList());
        $this->view->assign("zcztList", $this->model->getZcztList());

        $this->assignconfig('jingban', $this->auth->check('dahuinew/dljzyw/jingban'));

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            //更新issh字段
            $sql = "UPDATE fa_dahuinew_dljzyw SET issh = '上海' WHERE gsname LIKE '%上海%' and issh <> '上海'";
            Db::execute($sql);
            //
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $u = AuthGroupAccess::where('uid', $this->auth->id)->find();
            if ($u->group_id == 15) {
                $total = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->where('admin_id', $this->auth->id)
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->where('admin_id', $this->auth->id)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            } else {
                $total = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }


            $list = collection($list)->toArray();

            // $thismonth = date("Y-m");
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            if (isset($filter['htstart'])) {
                $sql = "select sum(htje) as num from fa_dahuinew_dljzyw where htstart = '{$filter['htstart']}' ";
                $money = Db::query($sql);
                $result = array("total" => $total, "rows" => $list, "extend" => ['money' => sprintf("%.2f", $money[0]['num'])]);
            } else {
                $result = array("total" => $total, "rows" => $list, "extend" => ['money' => ""]);
            }

            return json($result);
        }
        return $this->view->fetch();
    }

    public function index2()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where1 = " isxy = '未续约' ";
            $u = AuthGroupAccess::where('uid', $this->auth->id)->find();
            if ($u->group_id == 15) {
                $total = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->where($where1)
                    ->where('admin_id', $this->auth->id)
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->where($where1)
                    ->where('admin_id', $this->auth->id)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            } else {
                $total = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->where($where1)
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->where($where1)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }


            $list = collection($list)->toArray();

            // $thismonth = date("Y-m");
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            if (isset($filter['htstart'])) {
                if (isset($filter['xftype'])) {
                    $sql = "select sum(htje) as num from fa_dahuinew_dljzyw where htstart = '{$filter['htstart']}' and isxy = '未续约' and xftype = '{$filter['xftype']}' ";
                } else {
                    $sql = "select sum(htje) as num from fa_dahuinew_dljzyw where htstart = '{$filter['htstart']}' and isxy = '未续约'";
                }

                $money = Db::query($sql);
                $result = array("total" => $total, "rows" => $list, "extend" => ['money' => sprintf("%.2f", $money[0]['num'])]);
            } else {
                $result = array("total" => $total, "rows" => $list, "extend" => ['money' => ""]);
            }

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    if (isset($params['htstart']) && isset($params['htend'])) {
                        $params['htstart'] = trim($params['htstart']);
                        $params['htend'] = trim($params['htend']);
//                        $params['htend2'] = $params['htend'];
                        $params['htend2'] = date("Y-m", strtotime("+1 months", strtotime($params['htend'])));
                    }

                    if (isset($params['admin_id'])) {
                        $jbr = model('Admin')->get($params['admin_id']);
                        if ($jbr) {
                            $params['jbry'] = $jbr->nickname;
                        } else {
                            $params['jbry'] = "";
                        }
                    }

                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();

                    //----add fa_dahuinew_dljzmonth
                    //先删除原关联的记录
                    if (isset($params['htstart']) && isset($params['htend']) && strlen($params['htstart']) > 0 && $params['htend'] >= $params['htstart']) {

                        $from = $params['htstart'];
                        $to = $params['htend'];
                        $newny = $from;
                        for ($i = 0; $i < 48; $i++) {
                            $ny = \app\admin\model\dahuinew\Dljzmonth::where("dljzyw_id", $this->model->id)->where("sbyf", $newny)->find();
                            if (!$ny) {
                                $ny = new \app\admin\model\dahuinew\Dljzmonth;
                                $ny->dljzyw_id = $this->model->id;
                                $ny->sbyf = $newny;
                                $ny->jbry = $params['jbry'];
                            }
                            $ny->zczt = "未办理";
                            $ny->save();
                            $newny = date("Y-m", strtotime("+1 months", strtotime($newny)));
                            if ($newny > $to) {
                                break;
                            }
                        }
                    }

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 一键续费
     */
    public function yjxf($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    if (isset($params['htstart']) && isset($params['htend'])) {
                        $params['htstart'] = trim($params['htstart']);
                        $params['htend'] = trim($params['htend']);
//                        $params['htend2'] = $params['htend'];
                        $params['htend2'] = date("Y-m", strtotime("+1 months", strtotime($params['htend'])));
                    }

                    if (isset($params['admin_id'])) {
                        $jbr = model('Admin')->get($params['admin_id']);
                        $params['jbry'] = "";
                        if ($jbr) {
                            $params['jbry'] = $jbr->nickname;
                        }
                    }

                    $row->isxy = "已续约";
                    $row->save();

                    if ($params['htstart'] ==$row['htend2']) {
                        //时间连续了
                        $params['pid'] = $row->id;
                        $params['xftype'] = '续费';
                    }

                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();

                    //----add fa_dahuinew_dljzmonth
                    //先删除原关联的记录
                    if (isset($params['htstart']) && isset($params['htend']) && strlen($params['htstart']) > 0 && $params['htend'] >= $params['htstart']) {

                        $from = $params['htstart'];
                        $to = $params['htend'];
                        $newny = $from;
                        for ($i = 0; $i < 48; $i++) {
                            $ny = \app\admin\model\dahuinew\Dljzmonth::where("dljzyw_id", $this->model->id)->where("sbyf", $newny)->find();
                            if (!$ny) {
                                $ny = new \app\admin\model\dahuinew\Dljzmonth;
                                $ny->dljzyw_id = $this->model->id;
                                $ny->sbyf = $newny;
                                $ny->jbry = $params['jbry'];
                            }
                            $ny->zczt = "未办理";
                            $ny->save();
                            $newny = date("Y-m", strtotime("+1 months", strtotime($newny)));
                            if ($newny > $to) {
                                break;
                            }
                        }
                    }

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $row->htstart = date("Y-m", strtotime("+1 months", strtotime($row->htend)));
        $row->htend = date("Y-m", strtotime("+11 months", strtotime($row->htstart)));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    if (isset($params['admin_id'])) {
                        $jbr = model('Admin')->get($params['admin_id']);
                        $params['jbry'] = "";
                        if ($jbr) {
                            $params['jbry'] = $jbr->nickname;
                        }

                    }

                    if (isset($params['htstart']) && isset($params['htend'])) {
                        $params['htstart'] = trim($params['htstart']);
                        $params['htend'] = trim($params['htend']);
                        $params['htend2'] = $params['htend'];
                    }

//                    if ($this->auth->id != 38 && $this->auth->id != 1) {
//                        $xtime = time() - strtotime($row->create_time);
//                        if ($xtime > 15 * 86400) {
////                            超过15天
//                            $this->error(__('不能修改已超时'));//
//                        }
//                    }

                    $htstart = $row->htstart;
                    $htend = $row->htend;
                    $result = $row->allowField(true)->save($params);
                    Db::commit();

                    //修改合同日期后
                    if (isset($params['htstart']) && isset($params['htend']) && strlen($params['htstart']) > 0 && $params['htend'] >= $params['htstart']) {
                        $from = $params['htstart'];
                        $to = $params['htend'];
                        $newny = $from;
                        for ($i = 0; $i < 48; $i++) {
                            $ny = \app\admin\model\dahuinew\Dljzmonth::where("dljzyw_id", $row->id)->where("sbyf", $newny)->find();
                            if (!$ny) {
                                $ny = new \app\admin\model\dahuinew\Dljzmonth;
                                $ny->sbyf = $newny;
                                $ny->zczt = "未办理";
                            }
                            $ny->jbry = $params['jbry'];
                            $ny->dljzyw_id = $row->id;
                            $ny->save();
                            $newny = date("Y-m", strtotime("+1 months", strtotime($newny)));
                            if ($newny > $to) {
                                break;
                            }
                        }
                    }

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    if ($this->auth->id != 38 && $this->auth->id != 1) {
                        $xtime = time() - strtotime($v->create_time);
                        if ($xtime > 15 * 86400) {
                            $this->error(__('不能删除已超时'));
                        }
                    }
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    /**
     * 停止状态-- 停止月份==转出月份 -- 这个月没有正常缴纳
     */
    //http://dahui.test/admin/dahuinew/dljzyw/changezcstatus
    public function changezcstatus($ids = null)
    {
        $row = \app\admin\model\dahuinew\Dljzyw::get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($row->zczt == '正常') {
            $row->zczt = '已停止';
//            $row->htend2 = date("Y-m", strtotime("-1 months", time()));
            $row->htend2 = date("Y-m");
            $row->isxy = "停止";

        } else if ($row->zczt == '已停止') {
            $row->zczt = '正常';
//            $row->htend2 = $row->htend;
            $row->htend2 = date("Y-m", strtotime("+1 months", strtotime($row->htend)));
            $row->isxy = "未续约";
        }

        $row->save();
        $this->success("停止状态修改成功", null, ['zczt' => $row->zczt]);

    }


    /**
     * 申报状态
     */
    //http://dahui.test/admin/dahuinew/dljzyw/changesbstatus
    public function changesbstatus($ids = null)
    {
        $row = \app\admin\model\dahuinew\Dljzyw::get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $thismonth = date("Y-m");
        $sbinfo = json_decode($row->sbinfo, TRUE);//sbyf:  jbry
        if (!is_array($sbinfo)) {
            $sbinfo = [];
        }

        if ($row->sbzt == '未办理') {
            $row->sbzt = '已办理';
            $row->sbyf = $thismonth;

            $find = 0;
            foreach ($sbinfo as &$row3) {
                if ($row3['sbyf'] == $thismonth) {
                    $find = 1;
                    $row3['jbry'] = $this->auth->nickname;
                    break;
                }
            }
            if ($find == 0) {
                $sbinfo[] = array(
                    "sbyf" => $thismonth,
                    "jbry" => $this->auth->nickname
                );
            }
            $row->sbinfo = json_encode($sbinfo);

        } else if ($row->sbzt == '已办理') {
            $row->sbzt = '未办理';
            $row->sbyf = "";

            foreach ($sbinfo as &$row3) {
                if ($row3['sbyf'] == $thismonth) {
                    unset($row3);
                    break;
                }
            }
            $row->sbinfo = json_encode($sbinfo);
        }

        $row->save();
        $this->success("申报状态修改成功", null, ['sbzt' => $row->sbzt]);

    }

    //http://dahui.test/admin/dahuinew/dljzyw/getdsinfo?gsname=232
    public function getdsinfo()
    {
        $gsname = $this->request->request('gsname');
        $isdljzyw = $this->request->request('isdljzyw', 1);
        $isdljzyw = intval($isdljzyw);

        if (!$gsname) {
            $this->error('缺少公司信息！');
        }

        if ($isdljzyw == 0) {
            $data = \app\admin\model\dahuinew\Dljzyw::where("gsname", $gsname)->order("id desc")->limit(1)->find();
        } else {
            $data = \app\admin\model\dahuis\Sbgjj::where("gsname", $gsname)->order("id desc")->limit(1)->find();
        }

        $data['benyue'] = 0;
        if (date("Y-m") == date("Y-m", strtotime($data->create_time))) {
            //本月有记录
            $data['benyue'] = 1;
        }

        if (!$data) {
            if ($isdljzyw == 1) {
                $data = \app\admin\model\dahuinew\Dljzyw::where("gsname", $gsname)->order("id desc")->limit(1)->find();
            } else {
                $data = \app\admin\model\dahuis\Sbgjj::where("gsname", $gsname)->order("id desc")->limit(1)->find();
            }
        }

        if (!$data) {
            $this->error('找不到对应的公司！');
        }

        $this->success('查找成功', null, $data);//code=1 //和Api里的返回方式不一样
    }

    //
    public function import1()
    {
//        $u = AuthGroupAccess::where('uid', $this->auth->id)->find();
//        if ($u->group_id == 15) {
//            $total = $this->model
//                ->with(['admin'])
//                ->where('admin_id', $this->auth->id)
//                ->count();
//
//            $list = $this->model
//                ->with(['admin'])
//                ->where('admin_id', $this->auth->id)
//                ->select();
//        } else {
//            $total = $this->model
//                ->with(['admin'])
//                ->count();
//
//            $list = $this->model
//                ->with(['admin'])
//                ->select();
//        }
//
//
//        $list = collection($list)->toArray();
//        $fileName = "代理记账订单";
//
//        set_time_limit(0);
//        ini_set('memory_limit', '-1');
//
//        header('Content-Type: application/vnd.ms-execl');
//        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');
//
//        //打开php标准输出流
//        //以写入追加的方式打开
//        $fp = fopen('php://output', 'a');
//
//        //一次取5000条数据
//        $step = ceil($count/5000);
//
//        $title = array('业务类型', '缴纳年月', '淘宝名称', '身份证号', '客户姓名', '客户电话', '缴纳号码', '缴纳公司', '缴纳基数', '缴纳金额', '退款状态', '录入员', '审核员', '操作员');
//
//        //将标题写到标准输出中
//        fputcsv($fp, $title);
//
//        for($s = 0; $s < $step; $s++) {
//            $page_count = $s;
//            $page_size = 5000;
//            $offset = $page_count * $page_size;
//            $data = Db::query($sqlXX." limit 5000 offset ".$offset);
//            foreach ($data as &$row) {
//
//                $v = array(
//                    $row['businesstype'],
//                    "\t" .$row['paymentdate'],
//                    $row['taobaoname'],
//                    "\t" .$row['idnumber'],
//                    $row['kehuname'],
//                    $row['kehumobile'],
//                    "\t" .$row['paymentnumber'],
//                    $row['payingcompany'],
//                    $row['paymentbase'],
//                    $row['paymentamount'],
//                    $row['refundornot'],
//                    $row['luruman'],
//                    $row['auditman'],
//                    $row['opman']
//                );
//
//                fputcsv($fp, $v);
//            }
//            //每5000条数据就刷新缓冲区
//            ob_flush();
//            flush();
//        }
//        exit();
    }


}
